#include "env.h"

Env::Env(int type)
{
    if (type == MACHINE)
    {
        if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                         "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",
                         0, KEY_ALL_ACCESS,
                         &handle_) != ERROR_SUCCESS)
        {
            throw FailOpenKey();
        }
    }
    else if(::RegOpenKeyEx(HKEY_CURRENT_USER,
                           "Environment",
                           0, KEY_ALL_ACCESS,
                           &handle_) != ERROR_SUCCESS)
    {
        throw FailOpenKey();
    }
    read();
}
Env::~Env()
{
    ::RegCloseKey(handle_);
}

void Env::display()
{
    map<string, string>::const_iterator ci = vars_.begin();
    for(; ci != vars_.end(); ++ci)
    {
        std::cout << ci->first << " = " << ci->second << std::endl;
    }
}

void Env::read()
{
    DWORD env_index = 0;
    char env_name[1024];
    DWORD env_name_size = 1024;
    
    char env_value[1024];
    DWORD env_value_size = 1024;
    DWORD type;
    
    
    while(::RegEnumValue(handle_, env_index, env_name,
                       &env_name_size, 0, /*reserved*/
                       &type, (LPBYTE)env_value, &env_value_size) == ERROR_SUCCESS)
    {
        if (type == REG_EXPAND_SZ || type == REG_SZ)
        {
            //std::cout << env_name << " = " << env_value <<  std::endl;
            ++env_index;
            vars_[env_name] = env_value;
        }
        env_name_size = 1024;
        env_value_size = 1024;
    }
}
